import json
from time import sleep

import requests


def api_detect_language(KeywordList,TargetLanguage):
    if type(KeywordList)==list:
        pass
    else:
        KeywordList=['"'+KeywordList+'"']
    url = "http://irobotboxspider-hk.zhcxkj.com/BatchTranslation"
    headers = {'Content-Type': 'application/json'}
    username = "apiuser"
    password = "7ks0-t_0OpQ1Ira85"
    data = {
    "TargetLanguage": TargetLanguage,
    "Contents":KeywordList
}
    max_retry=3
    retry=0
    while retry<max_retry:
        sleep(2)
        res = requests.post(url=url, headers=headers, auth=(username, password),data=json.dumps(data))
        res = dict(res.json())
        if res["Message"]=="翻译成功":
            tanslate_result = res["result"]
            return tanslate_result
        else:
            pass
        retry = retry+1
    tanslate_api_data="调用翻译接口重试3次，仍然失败"
    return tanslate_api_data


# print(api_detect_language())
def api_Infringement(siteCode, CategoryPathId, keyWords):
    # 设置重试次数
    max_retries = 3
    retries = 0
    url = "http://riskapi.zhcxkj.com/Product/GetSensitive"
    headers = {'Content-Type': 'application/json'}
    username = "apiuser"
    password = "z8_h92c-o0Oxik1j"
    data = {  "input": {
                        "platformId": 1,
                        "siteCode": siteCode,
                        "riskLevel": 2,
                        "CategoryPathId": CategoryPathId,
                        "keyWords": keyWords}
    }

    while retries < max_retries:
        sleep(5)
        try:
            response = requests.post(url=url, headers=headers, auth=(username, password), data=json.dumps(data))
            res = dict(response.json())
            if res["status"]=="error":
                pass
            else:
                res = res["data"]
                return res
        except Exception as e:
            print(e)
        retries += 1
    # 如果最终没有成功，返回None或者抛出异常
    return None  # 或者 raise MaxRetryError("超过最大重试次数")
